var express = require('express');
var router = express.Router();
var url = require('url');
const units = require('../units/index')
const writeHead = {'Content-Type':'text/html;charset=utf-8'}

/* GET home page. */
router.get('/', function(req, res, next) {
  res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})
  return res.end(JSON.stringify(units('WARNING','当前访问禁止')))
});

// 测试列表读取
router.get('/query', function(req, res, next) {
  // const sql = 'SELECT * FROM websites'

  // 获取get参数
  var params = url.parse(req.url, true).query;
  let limit0 = 0, limit1 = 3
    limit0 = params.currentPage || limit0
    limit1 = params.pageSize || limit1
  // sql 查询
  const sql = `SELECT COUNT(*) as pagecount FROM websites;SELECT * FROM websites limit ${limit0 ? (limit0 - 1) * limit1 : limit0},${limit1}`

  const queryadd = require('../sqlconn/query')
  res.writeHead(200,writeHead)
  queryadd(sql, function(e) {
    if(!e) {
      return res.end(JSON.stringify(units('ERROR', '读取列表失败')))
    }
    // console.log(e)
    let count = e[0]
    const data = {
      count: count[0].pagecount,
      list: e[1],
      pagenum: limit0,
      pagesize: limit1
    }
    return res.end(JSON.stringify(units('SUCCESS', '读取成功', data)))
  })
  
});

// 测试列表读取
router.post('/query', function(req, res, next) {
  const sql = 'SELECT * FROM websites'
  const queryadd = require('../sqlconn/query')
  res.writeHead(200,writeHead)
  queryadd(sql, function(e) {
    if(!e) {
      return res.end(JSON.stringify(units('ERROR', '读取列表失败')))
    }
    // console.log(e)
    return res.end(JSON.stringify(units('SUCCESS', '读取成功', e)))
  })
  
});

module.exports = router;